﻿Imports System.Text

Public Class SelectQuestions
    Private idList As New List(Of Integer)
    Private type As Integer = -1
    Private needSelect As Boolean = False
    Private fillAnswerCount As Integer = 0
    Dim currentRow As ExamDataSet.questionRow = Nothing
    Dim stringDelimiter(2) As String

    Public Property SelectedIds As List(Of Integer)
        Get
            Return idList
        End Get
        Set(value As List(Of Integer))
            idList = value
        End Set
    End Property

    Public Property QueType As Integer
        Get
            Return type
        End Get
        Set(value As Integer)
            type = value
        End Set
    End Property

    Public Property ForSelect As Boolean
        Get
            Return needSelect
        End Get
        Set(value As Boolean)
            needSelect = value
        End Set
    End Property

    Private Sub SelectQuestions_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        stringDelimiter(0) = "|"
        stringDelimiter(1) = "|"
        If type <> -1 Then
            Me.QuestionTableAdapter.FillByType(Me.ExamDataSet.question, type)
        Else
            Me.QuestionTableAdapter.Fill(Me.ExamDataSet.question)
        End If
        If needSelect Then
            btnSelect.Visible = True
            dgvQueList.ReadOnly = False
            btnDelete.Visible = False
            rtxTitle.Enabled = False
            rtxQuestion.Enabled = False
            panelEdit.Visible = False
            'rtxOptions.Enabled = False
            cbType.Enabled = False
            'lblExample.Visible = False
            'rtbTips.Visible = False
            gbSelectAnswer.Enabled = False
            panelOptions.Enabled = False
            gbFillAnswer.Enabled = False
            gbJudgeAnswer.Enabled = False

        Else
            btnSelect.Visible = False
            btnDelete.Visible = True
            dgvQueList.ReadOnly = True
            dgvQueList.Columns("cbSelect").Visible = False
            rtxTitle.Enabled = True
            rtxQuestion.Enabled = True
            panelEdit.Visible = True

            'rtxOptions.Enabled = True
            'lblExample.Visible = True
            'rtbTips.Visible = True

        End If

    End Sub

    Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
        Dim que As String = rtxQuestion.Text

        Dim queType As Short = 0
        Dim right_answer As String = ""
        Dim options As String = ""
        Select Case cbType.SelectedIndex
            Case 0
                queType = 0
                options = buildOptions()
                right_answer = getSelectAnswer()
            Case 1
                queType = 1
                right_answer = getJudgeAnswer()
            Case 2
                queType = 2
                If Not validateFillAnswer(que) Then
                    Return
                End If
                right_answer = getFillAnswer()
                options = fillAnswerCount.ToString()
        End Select


        Dim title As String = rtxTitle.Text

        Try
            If String.IsNullOrEmpty(lblId.Text) Then
                Me.QuestionTableAdapter.InsertQuestion(que, queType, right_answer, title, options)
            Else
                Dim id As Integer = Integer.Parse(lblId.Text)
                Me.QuestionTableAdapter.UpdateById(que, queType, right_answer, title, options, id)
            End If
            MessageBox.Show("提交成功")
            clearAll()
            Me.QuestionTableAdapter.Fill(Me.ExamDataSet.question)
        Catch ex As Exception
            MessageBox.Show("提交失败，" + ex.Message)
        End Try
    End Sub

    Private Function buildOptions() As String
        Dim options As StringBuilder = New StringBuilder()
        options.Append(rtxSelectA.Text)
        options.Append("||")
        options.Append(rtxSelectB.Text)
        options.Append("||")
        options.Append(rtxSelectC.Text)
        options.Append("||")
        options.Append(rtxSelectD.Text)
        Return options.ToString()
    End Function

    Private Function getSelectAnswer() As String
        Dim answer As String = "A"
        If rbA.Checked Then
            answer = "A"
        ElseIf rbB.Checked Then
            answer = "B"
        ElseIf rbC.Checked Then
            answer = "C"
        ElseIf rbD.Checked Then
            answer = "D"
        End If
        Return answer
    End Function

    Private Function getJudgeAnswer() As String
        Dim answer As String = "1"
        If rbCorrect.Checked Then
            answer = "1"
        ElseIf rbWrong.Checked Then
            answer = "0"
        End If
        Return answer
    End Function

    Private Function getFillAnswer() As String
        Dim answer As StringBuilder = New StringBuilder()
        If fillAnswerCount > 0 Then
            answer.Append(rtxFill1.Text)
        End If
        If fillAnswerCount > 1 Then
            answer.Append("||")
            answer.Append(rtxFill2.Text)
        End If
        If fillAnswerCount > 2 Then
            answer.Append("||")
            answer.Append(rtxFill3.Text)
        End If
        If fillAnswerCount > 3 Then
            answer.Append("||")
            answer.Append(rtxFill4.Text)
        End If
        Return answer.ToString()
    End Function

    Private Function validateFillAnswer(que As String) As Boolean
        If fillAnswerCount < 1 Then
            fillAnswerCount = getFillCount(que)
            If fillAnswerCount < 1 Then
                MessageBox.Show("填空题至少要有一个空")
                Return False
            End If
        End If
        If fillAnswerCount > 4 Then
            MessageBox.Show("填空题不能多于4个空")
            Return False
        End If
        Return True
    End Function

    Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
        Try
            Dim searchStr As String = "%" + txtSearch.Text + "%"
            If needSelect Then
                Me.QuestionTableAdapter.FillByTitleQueAndType(Me.ExamDataSet.question, searchStr, type, searchStr)
            Else
                Me.QuestionTableAdapter.FillByTitleOrQue(Me.ExamDataSet.question, searchStr, searchStr)
            End If

        Catch ex As Exception

        End Try
    End Sub

    Private Sub btnSelect_Click(sender As Object, e As EventArgs) Handles btnSelect.Click
        Dim r As DataGridViewRow
        If dgvQueList.RowCount >= 1 Then
            For Each r In dgvQueList.Rows
                Dim cbc As DataGridViewCheckBoxCell = r.Cells("cbSelect")
                Dim id As Integer = r.Cells("questionId").Value
                If cbc.Value Then
                    idList.Add(id)
                End If
            Next r
        End If
        Me.Close()
    End Sub

    Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
        Dim question_id As Integer = Integer.Parse(lblId.Text)
        If MsgBox("是否删除该题目？", MsgBoxStyle.YesNo, "警告") = MsgBoxResult.Yes Then
            Try
                Me.QuestionTableAdapter.DeleteById(question_id)
                Me.Exam_questionsTableAdapter1.DeleteByQuestionId(question_id)
                MessageBox.Show("删除成功")
            Catch ex As Exception
                MessageBox.Show("删除失败，" + ex.Message)
            End Try
        End If
        Me.QuestionTableAdapter.Fill(Me.ExamDataSet.question)
    End Sub

    Private Sub dgvQueList_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgvQueList.CellClick
        clearAll()
        If e.RowIndex > -1 Then
            Dim row As ExamDataSet.questionRow = Me.ExamDataSet.question.Rows(e.RowIndex)
            currentRow = row
            updateTypeSelection(row)
            updateData()
        End If
    End Sub

    Private Sub updateTypeSelection(row As ExamDataSet.questionRow)
        Dim selectedType As Integer = row.type
        lblId.Text = row.id.ToString()
        rtxTitle.Text = row.title.ToString()
        rtxQuestion.Text = row.question.ToString()
        Select Case selectedType
            Case 0
                cbType.SelectedIndex = 0
            Case 1
                cbType.SelectedIndex = 1
            Case 2
                cbType.SelectedIndex = 2
        End Select
    End Sub

    Private Sub dgvQueList_DataBindingComplete(sender As Object, e As DataGridViewBindingCompleteEventArgs) Handles dgvQueList.DataBindingComplete
        If Me.ExamDataSet.question.Count > 0 Then
            Dim row As ExamDataSet.questionRow = Me.ExamDataSet.question.Rows(0)
            currentRow = row
            updateTypeSelection(row)
        End If
    End Sub

    Private Sub btnClear_Click(sender As Object, e As EventArgs)
        clearAll()
    End Sub

    Private Sub clearAll()
        lblId.Text = ""
        rtxTitle.Text = ""
        rtxSelectA.Text = ""
        rtxSelectB.Text = ""
        rtxSelectC.Text = ""
        rtxSelectD.Text = ""
        rtxQuestion.Text = ""
        fillAnswerCount = 0
        rtxFill1.Text = ""
        rtxFill2.Text = ""
        rtxFill3.Text = ""
        rtxFill4.Text = ""
        rtxFill1.AllowEmpty = True
        rtxFill2.AllowEmpty = True
        rtxFill3.AllowEmpty = True
        rtxFill4.AllowEmpty = True
        rbA.Checked = True
        rbCorrect.Checked = True
        currentRow = Nothing
    End Sub

    Private Sub updateData()
        Select Case currentRow.type
            Case 0
                Dim options() As String = currentRow.options.Split(stringDelimiter, StringSplitOptions.RemoveEmptyEntries)
                rtxSelectA.Text = options(0)
                rtxSelectB.Text = options(1)
                rtxSelectC.Text = options(2)
                rtxSelectD.Text = options(3)
                Select Case currentRow.right_answer

                    Case "A"
                        rbA.Checked = True
                    Case "B"
                        rbB.Checked = True
                    Case "C"
                        rbC.Checked = True
                    Case "D"
                        rbD.Checked = True
                End Select
            Case 1
                If currentRow.right_answer.Equals("0") Then
                    rbWrong.Checked = True
                Else
                    rbCorrect.Checked = True
                End If
            Case 2
                Dim answers As String() = currentRow.right_answer.Split(stringDelimiter, StringSplitOptions.RemoveEmptyEntries)
                If answers.Count > 0 Then
                    rtxFill1.Text = answers(0)
                End If
                If answers.Count > 1 Then
                    rtxFill2.Text = answers(1)
                End If
                If answers.Count > 2 Then
                    rtxFill3.Text = answers(2)
                End If
                If answers.Count > 3 Then
                    rtxFill4.Text = answers(3)
                End If
        End Select
    End Sub

    Private Sub cbType_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cbType.SelectedIndexChanged
        Select Case cbType.SelectedIndex
            Case 0
                lblShow.Text = "选择题"

                lblTitleExample.Text = "示例：关于季节"
                lblQueExample.Text = "示例：请问北京有多少个季节？"
                panelOptions.Visible = True
                gbSelectAnswer.Visible = True
                gbFillAnswer.Visible = False
                gbJudgeAnswer.Visible = False

                rtxSelectA.AllowEmpty = False
                rtxSelectB.AllowEmpty = False
                rtxSelectC.AllowEmpty = False
                rtxSelectD.AllowEmpty = False


                rtxFill1.AllowEmpty = True
                rtxFill2.AllowEmpty = True
                rtxFill3.AllowEmpty = True
                rtxFill4.AllowEmpty = True
                type = 0
                If currentRow IsNot Nothing Then
                    If currentRow.type = 0 Then
                        updateData()
                    Else
                        clearAll()
                    End If

                End If
            Case 1
                lblShow.Text = "判断题"
                panelOptions.Visible = False
                gbSelectAnswer.Visible = False
                gbJudgeAnswer.Visible = True
                gbFillAnswer.Visible = False
                lblTitleExample.Text = "示例：如何穿衣"
                lblQueExample.Text = "示例：判断下面的语句是否正确：北京的冬天不需要穿羽绒服。"
                type = 1

                rtxSelectA.AllowEmpty = True
                rtxSelectB.AllowEmpty = True
                rtxSelectC.AllowEmpty = True
                rtxSelectD.AllowEmpty = True


                rtxFill1.AllowEmpty = True
                rtxFill2.AllowEmpty = True
                rtxFill3.AllowEmpty = True
                rtxFill4.AllowEmpty = True
                If currentRow IsNot Nothing Then
                    If currentRow.type = 1 Then
                        updateData()
                    Else
                        clearAll()
                    End If
                End If
            Case 2
                lblShow.Text = "填空题"
                panelOptions.Visible = False
                gbSelectAnswer.Visible = False
                gbJudgeAnswer.Visible = False
                gbFillAnswer.Visible = True
                lblTitleExample.Text = "示例：雾霾"
                lblQueExample.Text = "示例：中国首都叫[[]]，它的雾霾指数[[]]经常非常高。每一个需要填空的地方要加上‘[[]]’,每个填空题里面不能超过四个空（可以少于四个）。"
                type = 2
                rtxSelectA.AllowEmpty = True
                rtxSelectB.AllowEmpty = True
                rtxSelectC.AllowEmpty = True
                rtxSelectD.AllowEmpty = True

                If currentRow IsNot Nothing Then
                    If currentRow.type = 2 Then
                        If currentRow.type = 2 Then
                            updateData()
                        Else
                            clearAll()

                        End If
                    End If
                End If
        End Select
    End Sub

    Private Sub 文件ToolStripMenuItem_Click(sender As Object, e As EventArgs)
        ExamMgm.Show()
        Me.Hide()
    End Sub

    Private Sub 学生管理ToolStripMenuItem1_Click(sender As Object, e As EventArgs)
        Me.Hide()
        StudentMgm.Show()
    End Sub

    Private Sub 退出ToolStripMenuItem_Click(sender As Object, e As EventArgs)
        End
    End Sub

    Private Sub ExamMgmToolStripMenuItem_Click(sender As Object, e As EventArgs)
        ExamMgm.Show()
        Me.Hide()
    End Sub

    Private Sub StudentMgmToolStripMenuItem1_Click(sender As Object, e As EventArgs)
        StudentMgm.Show()
        Me.Hide()
    End Sub

    Private Sub panelOptions_VisibleChanged(sender As Object, e As EventArgs) Handles panelOptions.VisibleChanged
        If panelOptions.Visible Then
            rtxSelectA.AllowEmpty = False
            rtxSelectB.AllowEmpty = False
            rtxSelectC.AllowEmpty = False
            rtxSelectD.AllowEmpty = False
        Else
            rtxSelectA.AllowEmpty = True
            rtxSelectB.AllowEmpty = True
            rtxSelectC.AllowEmpty = True
            rtxSelectD.AllowEmpty = True
        End If
    End Sub

    Private Sub SelectQuestions_FormClosed(sender As Object, e As FormClosedEventArgs) Handles MyBase.FormClosed
        If Not needSelect Then
            End
        End If
    End Sub

    Private Sub rtxQuestion_TextChanged(sender As Object, e As EventArgs) Handles rtxQuestion.TextChanged
        If type = 2 Then
            Dim que As String = rtxQuestion.Text
            fillAnswerCount = getFillCount(que)
            rtxFill1.AllowEmpty = True
            rtxFill2.AllowEmpty = True
            rtxFill3.AllowEmpty = True
            rtxFill4.AllowEmpty = True
            If fillAnswerCount > 0 Then
                rtxFill1.AllowEmpty = False
            End If
            If fillAnswerCount > 1 Then
                rtxFill2.AllowEmpty = False
            End If
            If fillAnswerCount > 2 Then
                rtxFill3.AllowEmpty = False
            End If
            If fillAnswerCount > 3 Then
                rtxFill4.AllowEmpty = False
            End If
        End If
    End Sub

    Private Function getFillCount(que As String) As Integer
        Dim count As Integer = 0
        While que.Contains("[[]]")
            Dim start As Integer = InStr(que, "[[]]")
            que = que.Remove(start - 1, 4)
            count = count + 1
        End While
        Return count
    End Function

    Private Sub ExitToolStripMenuItem_Click(sender As Object, e As EventArgs)
        End
    End Sub

    Private Sub ImportToolStripMenuItem_Click(sender As Object, e As EventArgs)
        ImportQuesions()

    End Sub

    Public Sub ImportQuesions()
        Dim fdia As OpenFileDialog = New OpenFileDialog()
        fdia.Filter = "Excel 文件（.xls)|*.xls|所有文件|*.*"
        fdia.ShowDialog()
        Dim fileName = fdia.FileName
        Dim line As Integer = 1
        Dim success As Integer = 0
        If Not String.IsNullOrEmpty(fileName) Then
            Try
                Dim xlExcel As Excel.Application = New Excel.Application()
                Dim xlBook As Excel.Workbook
                xlBook = xlExcel.Workbooks.Open(fileName)
                xlExcel.Visible = False
                Dim xlSheet As Excel.Worksheet = xlBook.Worksheets(1)

                xlSheet.Activate()

                For index = 2 To xlSheet.UsedRange.Rows.Count
                    line = line + 1
                    Dim queName As String = xlSheet.Cells(index, 1).Value
                    If String.IsNullOrEmpty(queName) Then
                        MessageBox.Show("导入试题失败！在第" + line.ToString() + "行, 题目标题不能为空。")
                        Continue For
                    End If
                    Dim m_type As String = Integer.Parse(xlSheet.Cells(index, 2).Value)
                    If m_type <> 0 And m_type <> 1 And m_type <> 2 Then
                        MessageBox.Show("导入试题失败！在第" + line.ToString() + "行，类型不符合规则。应为0（选择题）1（判断题）2（填空题）")
                        Continue For
                    End If
                    Dim question As String = xlSheet.Cells(index, 3).Value
                    If String.IsNullOrEmpty(question) Then
                        MessageBox.Show("导入试题失败！在第" + line.ToString() + "行, 题目内容不能为空。")
                        Continue For
                    End If
                    Dim answer As String = xlSheet.Cells(index, 4).Value
                    Dim options As String = xlSheet.Cells(index, 5).Value
                    Select Case m_type
                        Case 0
                            If Not answer.ToUpper().Equals("A") And Not answer.ToUpper().Equals("B") And Not answer.ToUpper().Equals("C") And Not answer.ToUpper().Equals("D") Then
                                MessageBox.Show("导入试题失败！在第" + line.ToString() + "行，选择题答案不符合规则，应为A/B/C/D。")
                                Continue For

                            End If
                            If options.Split(ExamGlobal.Spliter, StringSplitOptions.RemoveEmptyEntries).Count <> 4 Then
                                MessageBox.Show("导入试题失败！在第" + line.ToString() + "行，选择题选项不符合规则，应该4个选项。")
                                Continue For
                            End If
                        Case 1
                            If Not answer.Equals("0") And Not answer.Equals("1") Then
                                MessageBox.Show("导入试题失败！在第" + line.ToString() + "行，判断题答案不符合规则，应该0（错误）或者1（正确）。")
                                Continue For
                            End If
                        Case 2
                            options = answer.Split(ExamGlobal.Spliter, StringSplitOptions.RemoveEmptyEntries).Count
                            Dim del() As String = {"[", "[", "]", "]"}
                            Dim quesCount = question.Split(del, StringSplitOptions.RemoveEmptyEntries).Count
                            If question.StartsWith("[[]]") Then
                                quesCount = quesCount + 1
                            End If
                            If question.EndsWith("[[]]") Then
                                quesCount = quesCount + 1
                            End If
                            If options <> quesCount - 1 Then
                                MessageBox.Show("导入试题失败！在第" + line.ToString() + "行，填空题答案和题目空数量不等。")
                                Continue For
                            End If
                    End Select

                    Me.QuestionTableAdapter.InsertQuestion(question, m_type, answer, queName, options)
                    success = success + 1
                Next
                xlBook.Close()
                xlExcel.Quit()
                xlExcel = Nothing
                If success > 0 Then
                    MessageBox.Show("导入试题成功！共导入" + success.ToString() + "题目。")
                Else
                    MessageBox.Show("没有导入题目。")
                End If
                Me.QuestionTableAdapter.Fill(Me.ExamDataSet.question)
            Catch ex As System.Exception
                System.Windows.Forms.MessageBox.Show("导入试题失败！在第" + line.ToString() + "行。错误信息：" + ex.Message)
            End Try
        End If
    End Sub

    Private Sub CreateNewToolStripMenuItem_Click(sender As Object, e As EventArgs)
        CreateNewQuestion()
    End Sub

    Public Sub CreateNewQuestion()
        Dim cq As CreateQuestion = New CreateQuestion()
        cq.ShowDialog()
        Me.QuestionTableAdapter.Fill(Me.ExamDataSet.question)
    End Sub
End Class